package com.cal.calonecal.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author 76004
 * @apiNote
 * @date 2023/5/11 21:58
 */
@Configuration
@ConfigurationProperties("pool-config")
@EnableAsync
@Data
public class PoolConfiguration {

    //核心线程池大小
    private Integer corePoolSize;

    //最大线程数
    private Integer maxPoolSize;

    //队列容量
    private Integer queueCapacity;

    //活跃时间
    private Integer keepAliveSeconds;

    //线程名字前缀
    private String threadNamePrefix;

    @Bean(name = "exam-judge-pool")
    public Executor createThreadPoolExecutor(){
        System.out.println(this.maxPoolSize);
        ThreadPoolTaskExecutor threadPoolExecutor = new ThreadPoolTaskExecutor();
        threadPoolExecutor.setCorePoolSize(this.corePoolSize);
        threadPoolExecutor.setMaxPoolSize(this.maxPoolSize);
        threadPoolExecutor.setKeepAliveSeconds(this.keepAliveSeconds);
        threadPoolExecutor.setQueueCapacity(this.queueCapacity);
        threadPoolExecutor.setThreadNamePrefix(this.threadNamePrefix);

        // setRejectedExecutionHandler：当pool已经达到max size的时候，如何处理新任务
        // CallerRunsPolicy：不在新线程中执行任务，而是由调用者所在的线程来执行
        threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolExecutor.initialize();
        return threadPoolExecutor;
    }
}
